<?php
include_once('phpheader.inc.php');

$instance; // the class name of controller to invoke
$req_uri = getParameter("route");
foreach ($route as $rt=>$new_route) {
	if ($req_uri == $rt) {
		$req_uri = str_replace($req_uri, $new_route, $rt);
		break;
	}
}

$router = new Router();
$router->parse_controller($req_uri);

// assign to module/controller/method
$controller = ucfirst($router->class.'Controller');
$subdir = $router->subdir;
$method = $router->method;
$arguments = $router->segments;

// debugging the MVC pattern uncomment below
//echo "Controller = ".$controller."<br>";
//echo "Method = ".$method."<br>Arguments = ";
//print_r($arguments);
//die();
if ($subdir == "") {
    $classFile = WEB_ROOT . '/app/controllers/' . $controller . EXT;
} else {
    $classFile = WEB_ROOT . '/app/controllers/' . $subdir .'/' . $controller . EXT;
}

//echo $classFile.'='.$class;
if (file_exists($classFile)) {
	require_once ($classFile);
	//echo $classFile.'<br>';
	if (class_exists($controller)) {
		$instance = new $controller();
	} else {
		die("class [$controller] does not exist.");
	}
} else {
	die('['.$classFile . '] DOES NOT EXIST	');
}
if (method_exists($controller,$method)) {
    // this does all the work of calling the controller
    call_user_func_array(array($instance, $method), $arguments);
} else {
    die('['.$controller . '->' . $method. '] DOES NOT EXIST	');
}
?>